package com.agent.web;

import com.agent.dto.FriendUpdateDTO;
import com.agent.entity.Friend;
import com.agent.entity.GroupFriend;
import com.agent.entity.User;
import com.agent.service.FriendService;
import com.agent.service.GroupFriendService;
import com.agent.service.GroupService;
import com.agent.service.UserService;
import com.agent.utils.UserContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/web/friend")
public class FriendController {

    private final FriendService friendService;
    private final GroupService groupService;
    private final GroupFriendService groupFriendService;
    private final UserService userService;

    // 修改当前登录用户的群友信息（若不存在则创建）
    @PutMapping("/update")
    public ResponseEntity<?> update(@RequestBody FriendUpdateDTO req) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();

        Friend me = friendService.getOne(new LambdaQueryWrapper<Friend>().eq(Friend::getUserId, userId), false);
        if (me == null) {
            // 不存在，则创建
            me = Friend.builder()
                    .userId(userId)
                    .nickname(req.getNickname())
                    .email(req.getEmail())
                    .joinTime(LocalDateTime.now())
                    .build();
            friendService.save(me);
        } else {
            // 修改
            if (req.getNickname() != null) me.setNickname(req.getNickname());
            if (req.getEmail() != null) me.setEmail(req.getEmail());
            friendService.updateById(me);
        }

        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", me.getId());
        return ResponseEntity.ok(resp);
    }

    // 加入群组
    @PostMapping("/join")
    public ResponseEntity<?> join(@RequestParam("groupId") Long groupId) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getId, userId));
        // 校验群组存在
        if (groupService.getById(groupId) == null) {
            resp.put("code", 404);
            resp.put("msg", "Group not found");
            return ResponseEntity.status(404).body(resp);
        }

        // 获取或创建 Friend 记录
        Friend me = friendService.getOne(new LambdaQueryWrapper<Friend>().eq(Friend::getUserId, userId), false);
        if (me == null) {
            me = Friend.builder()
                    .userId(userId)
                    .nickname(user.getUsername())
                    .joinTime(LocalDateTime.now())
                    .email(user.getEmail())
                    .build();
            friendService.save(me);
        }

        // 已存在关联直接返回
        long cnt = groupFriendService.count(new LambdaQueryWrapper<GroupFriend>()
                .eq(GroupFriend::getGroupId, groupId)
                .eq(GroupFriend::getFriendId, me.getId()));
        if (cnt == 0) {
            groupFriendService.save(GroupFriend.builder().groupId(groupId).friendId(me.getId()).build());
        }

        resp.put("code", 0);
        resp.put("msg", "ok");
        return ResponseEntity.ok(resp);
    }

    // 退出群组
    @DeleteMapping("/leave")
    public ResponseEntity<?> leave(@RequestParam("groupId") Long groupId) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();

        Friend me = friendService.getOne(new LambdaQueryWrapper<Friend>().eq(Friend::getUserId, userId), false);
        if (me != null) {
            // 删除关联
            groupFriendService.remove(new LambdaQueryWrapper<GroupFriend>()
                    .eq(GroupFriend::getGroupId, groupId)
                    .eq(GroupFriend::getFriendId, me.getId()));
            // 删除群友数据
            friendService.removeById(me.getId());
        }

        resp.put("code", 0);
        resp.put("msg", "ok");
        return ResponseEntity.ok(resp);
    }
}
